# -*- coding: utf-8 -*-

import os
import random
import string
from datetime import datetime
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import HttpResponseBadRequest
from django.conf import settings

from firstDjango.exceptions import FormException
from index.common.tool import get_current_domain_name


def upload_image(request: WSGIRequest):
    if request.method != "POST":
        return HttpResponseBadRequest()
    file = request.FILES.get("file", None)  # 获取上传的文件，如果没有文件，则默认为None
    if not file:
        raise FormException("未选择文件")
    file_name = ''.join(random.sample(string.ascii_letters + string.digits, 20)) + '.' + file.name.split(".")[-1]
    image_path = os.path.join(settings.STATIC_ROOT, file_name)
    destination = open(image_path, 'wb+')  # 打开特定的文件进行二进制的写操作
    for chunk in file.chunks():  # 分块写入文件
        destination.write(chunk)
    destination.close()
    return {
        "file_url": get_current_domain_name(request) + settings.STATIC_URL + file_name,
        "file_uri": file_name
    }